package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@WebServlet("/uploadServlet")
@MultipartConfig(maxFileSize = 2 * 1024 * 1024)//控制上传文件的大小为2MB
public class UploadServlet extends HttpServlet {

    private List<String> allowImgTypes = Arrays.asList("image/jpeg", "image/png", "image/jpg");
    private MultipartConfig config = UploadServlet.class.getAnnotation(MultipartConfig.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取请求中的文件
            Part part = request.getPart("bookImg");

            //获取文件类型
            String contentType = part.getContentType();
            boolean contains = allowImgTypes.contains(contentType);
            if (contains) {
                //如何设置文件保存位置
                String uploadFilePath = request.getSession().getServletContext().getRealPath("images/");
                File file = new File(uploadFilePath);

                if (!file.exists()) {//判断路径是否存在，不存在则创建
                    file.mkdirs();//创建目录
                }
                //设置文件名（UUID 随机字符串）
                String fileName = UUID.randomUUID().toString().concat(".jpg");
                //开始保存上传的文件
                part.write(uploadFilePath.concat(fileName));
                //设置提示信息：
                request.setAttribute("msg", "文件上传成功！<br> 文件名："
                        .concat(fileName).concat("文件保存位置：".concat(uploadFilePath)));
            } else {
                request.setAttribute("msg", "文件上传失败！文件类型是能是：image/png,image/jpeg,image/jpg");
            }
        } catch (IllegalStateException e) {
            request.setAttribute("msg", "文件上传失败文件最大为2MB");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "文件上传失败！<br> 文件名异常信息："
                    .concat(e.getMessage()));
        }
        request.getRequestDispatcher("upload.jsp").forward(request, response);
    }

}
